package com.lu.sys.controller;


import com.alibaba.fastjson2.JSONObject;
import com.lu.common.vo.Result;
import com.lu.sys.mapper.FileMapper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 上传控制器
 */
@Slf4j
@RestController
@Api(tags = "文件上传的接口")
@RequestMapping(value = "/file")
public class UploadController extends BaseController{


    @Value("${files.upload.path}")
    private String uploadFilePath;
    @Resource
    private FileMapper fileMapper;
    /**
     * 上传文件
     * @param fujian
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/upload_re")
    public Result<?> Upload(@RequestParam("files")MultipartFile files[], @RequestParam("fileType") Integer fileType) throws Exception
    {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<com.lu.sys.entity.File> filelist = new ArrayList<>();
        for(int i=0;i<files.length;i++){
            String fileName = files[i].getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID()+suffixName;
            File dest = new File(uploadFilePath + fileName);
            com.lu.sys.entity.File file = new com.lu.sys.entity.File();
            file.setFileName(fileName);
            file.setFileType(fileType);
            file.setFileDel(0);
            int fileId = fileMapper.insertSelective(file);
            filelist.add(file);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                files[i].transferTo(dest);
            } catch (Exception e) {
                log.error("{}",e);
                return Result.fail("程序错误，请重新上传");
            }
        }
        hashMap.put("success",1);
        hashMap.put("success","文件上传成功");
        hashMap.put("fileName",filelist.get(0).getFileName());
        hashMap.put("fileId",filelist.get(0).getId());
        return Result.success(hashMap);
    }

    private String getFolder(String path) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        path += "/" + formater.format(new Date());
        File dir = new File(this.getPhysicalPath(path));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                return "";
            }
        }
        return path;
    }

    /**
     * 根据传入的虚拟路径获取物理路径
     *
     * @param path
     * @return
     */
    private String getPhysicalPath(String path) {
        String servletPath = this.request.getServletPath();
        String realPath = this.request.getSession().getServletContext()
                .getRealPath(servletPath);
        return new File(realPath).getParent() +"/" +path;
    }

    @GetMapping("/preview/{fileName}")
    public ResponseEntity<InputStreamResource> preview(@PathVariable String fileName) throws IOException {


        File file = new File(uploadFilePath + fileName);
        FileInputStream fis = new FileInputStream(file);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(fis));
    }


    @GetMapping("/download/{fileName}")
    public void downloadFile(@PathVariable String fileName,HttpServletResponse response) {
        // 指定要下载的文件路径
        String filePath = uploadFilePath+fileName;
        File file = new File(filePath);

        try {
            // 设置响应类型
            response.setContentType("application/octet-stream");

            // 设置响应的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int b = fis.read(buffer);
            while (b != -1) {
                response.getOutputStream().write(buffer, 0, b);
                b = fis.read(buffer);
            }

            // 关闭流
            fis.close();
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
